package filters;

import common.Result;
import common.ResultCodeEnum;
import util.JwtHelper;
import util.WebUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

// 修改URL模式，同时包含/headline/*和/history/*
@WebFilter({"/headline/*", "/history/*"})
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


// 获取请求路径
        String requestURI = request.getRequestURI();

        // 排除不需要拦截的路径
        // 允许添加浏览记录的请求通过（即使未登录，由Controller处理）
        if (requestURI.contains("/history/add")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 获取请求头中的token
        String token = request.getHeader("token");
        // 验证token是否存在且未过期
        boolean isTokenValid = token != null && !JwtHelper.isExpiration(token);

        if (isTokenValid) {
            // token有效，放行请求
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // token无效或不存在，返回未登录状态
            WebUtil.writeJson(response, Result.build(null, ResultCodeEnum.NOTLOGIN));
        }
    }
}
